package com.yanqu.road.server.manger.activity.suitang;

import com.yanqu.road.entity.activity.ActivityConfig;
import com.yanqu.road.entity.activity.ActivityInfo;
import com.yanqu.road.entity.activity.suitang.config.*;
import com.yanqu.road.entity.activity.suitang.enums.eSuiTangStage;
import com.yanqu.road.entity.enums.eActivityConfigType;
import com.yanqu.road.entity.enums.eActivityType;
import com.yanqu.road.entity.enums.eSkillType;
import com.yanqu.road.entity.player.UserHistoryAttribute;
import com.yanqu.road.entity.player.UserInfo;
import com.yanqu.road.entity.union.activitygroup.UnionActivityGroup;
import com.yanqu.road.logic.activity.suitang.SuiTangMapLogic;
import com.yanqu.road.logic.bussiness.activity.SuiTangActivityBusiness;
import com.yanqu.road.logic.bussiness.player.UserHistoryAttributeBussiness;
import com.yanqu.road.logic.helper.UnionActivityGroupHelper;
import com.yanqu.road.pb.activity.TongBingProto;
import com.yanqu.road.pb.activity.suitang.SuiTang;
import com.yanqu.road.server.TempMgr;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.activity.suitang.SuiTangModule;
import com.yanqu.road.server.gameplayer.module.patrons.PatronsModule;
import com.yanqu.road.server.gameplayer.module.player.PlayerModule;
import com.yanqu.road.server.manger.activity.ActivityMgr;
import com.yanqu.road.server.manger.activity.NormalActivityMgr;
import com.yanqu.road.server.manger.activity.curio.CurioMgr;
import com.yanqu.road.server.manger.player.GamePlayerMgr;
import com.yanqu.road.server.manger.player.UserMgr;
import com.yanqu.road.server.manger.union.GameUnionActivityGroupMgr;
import com.yanqu.road.server.protocol.CrossProtocol;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.utils.RandomHelper;
import com.yanqu.road.utils.property.Property;
import com.yanqu.road.utils.property.PropertyHelper;
import com.yanqu.road.utils.string.StringUtils;

import java.math.BigInteger;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

public class SuiTangMgr extends TempMgr {

    private static SuiTangConfigSync config = null;

    private static RandomHelper randomHelper = new RandomHelper();

    private static final Set<Long> userIdSet = new HashSet<>(); // 赚速有变化的玩家ID

    private static final Map<Integer, Set<Integer>> refreshGroupActivityMap = new ConcurrentHashMap<>();

    @Override
    public boolean init() throws Exception {
        CurioMgr.addSyncListener(eSkillType.CurioSuiTangTeamMaxSoldierAdd.getValue(), (skillType, skillData, player) -> SuiTangMgr.syncSuiTangPatronsAbility(player, true));
        return reload();
    }

    /**
     * 重新加载活动
     */
    public static void reloadActivityData() {
        getLogger().info("reload SuiTangActivity start");
        List<ActivityInfo> list = NormalActivityMgr.getOpenActivityInfoList(eActivityType.SuiTang.getValue());
        if (list.isEmpty()) {
            config = null;
            getLogger().info("reload SuiTangActivity end, no activity in show time.");
            return;
        }
        ActivityInfo activityInfo = list.get(0);

        loadConfigFromDb(activityInfo);
        getLogger().info("reload SuiTangActivity end, activityId {}.", config.getActivityInfo().getActivityId());

        for (GamePlayer player : GamePlayerMgr.getAllOnlinePlayer()) {
            player.getModule(SuiTangModule.class).suiTangLogin();
        }
    }

    /**
     * 数据库加载配置
     */
    private static void loadConfigFromDb(ActivityInfo activityInfo) {
        if (activityInfo == null) {
            return;
        }
        int activityId = activityInfo.getActivityId();
        Map<String, ActivityConfig> activityConfigMap = NormalActivityMgr.getActivityConfigMap(activityInfo.getActivityId());

        SuiTangConfigSync tmpConfig = new SuiTangConfigSync();
        tmpConfig.setActivityId(activityId);
        tmpConfig.setActivityInfo(activityInfo);
        tmpConfig.setBuffConfigMap(SuiTangActivityBusiness.getGenericConfigMap(activityId, SuiTangBuffConfig.class));
        tmpConfig.setCityConfigMap(SuiTangActivityBusiness.getGenericConfigMap(activityId, SuiTangCityConfig.class));
        tmpConfig.setCityTypeConfigMap(SuiTangActivityBusiness.getGenericConfigMap(activityId, SuiTangCityTypeConfig.class));
        tmpConfig.setRankConfigMap(SuiTangActivityBusiness.getGenericConfigMap(activityId, SuiTangRankConfig.class));
        tmpConfig.setGuessConfigMap(SuiTangActivityBusiness.getGenericConfigMap(activityId, SuiTangGuessConfig.class));
        tmpConfig.setActivityConfigMap(activityConfigMap);
        tmpConfig.getParamConfig().initParamConfig(activityConfigMap);
        tmpConfig.setCityConnectMap(SuiTangMapLogic.getCityConnectMapConfig());
        tmpConfig.calcTimeList();
        tmpConfig.calcCampBoxConfig();
        config = tmpConfig;
    }

    /**
     * 同步逐鹿隋唐门客数据
     * @param isRefreshMaxSoldier 是否只刷新兵力上限
     */
    public static void syncSuiTangPatronsAbility(GamePlayer player, boolean isRefreshMaxSoldier) {
        if (config == null || !ActivityMgr.activityInShowTime(config.getActivityInfo())) {
            return;
        }

        // 判断活动开始
        if (!config.inEnterActivityTime()|| !player.getModule(SuiTangModule.class).hasCamp()) {
            return;
        }

        // 同步带兵上限
        SuiTang.CrossSuiTangUpdatePatronsReqMsg.Builder builder = SuiTang.CrossSuiTangUpdatePatronsReqMsg.newBuilder();
        builder.setActivityId(config.getActivityId());
        builder.setUserId(player.getUserId());
        builder.setTotalAbility(player.getModule(PatronsModule.class).getSuiTangPatronsNAbility(config.getParamConfig().getSuiTangPlayerEveryJobPatronsNumMax()));
        builder.setSoldierAddition(player.getModule(PatronsModule.class).getSuiTangSoldierAddition());
        builder.setPatronsNSum(player.getModule(PatronsModule.class).getSuiTangPatronsNSum(config.getParamConfig().getSuiTangPlayerEveryJobPatronsNumMax()));
        builder.setPatronsTotalNum(player.getModule(PatronsModule.class).getUserPatronsList().size());
        builder.setIsRefreshMaxSoldier(isRefreshMaxSoldier);
        builder.setPatronsTotalAbility(player.getModule(PatronsModule.class).getTotalPatronsAbility().longValue());
        player.sendUnionActivityGroupPacket(CrossProtocol.C2_CROSS_SUI_TANG_PATRONS_SYNC, builder, config.getActivityId());
    }

    /**
     * 上传商会赚速变化
     */
    public static void uploadUnionEarnSpeedChange() {
//        if (userIdSet.isEmpty()) {
//            return;
//        }
//
//        if (config == null || config.getSuiTangStage() != eSuiTangStage.JoinTime) {
//            return;
//        }
//
//        ArrayList<Long> userIdList;
//        synchronized (userIdSet) {
//            userIdList = new ArrayList<>(userIdSet);
//            userIdSet.clear();
//        }
//
//        int activityId = config.getActivityInfo().getActivityId();
//
//        Map<Integer, TongBingProto.CrossTongBingGetMemberRespMsg.Builder> groupBuilderMap = new HashMap<>();
//        for (long userId : userIdList) {
//            UserInfo userInfo = UserMgr.getUserInfo(userId);
//            if (userInfo == null) {
//                continue;
//            }
//            int groupId = GameUnionActivityGroupMgr.getGroupId(activityId, userId);
//            if (groupId == UnionActivityGroupHelper.NO_GROUP_ID) {
//                continue;
//            }
//
//            TongBingProto.TongBingUnionMemberMsg.Builder tmp = TongBingProto.TongBingUnionMemberMsg.newBuilder();
//            tmp.setUserId(userInfo.getUserId());
//            tmp.setUnionUid(userInfo.getUnionUid());
//            tmp.setEarnSpeed(userInfo.getEarnSpeed().toString());
//            tmp.setPatronsTopAbility(getTopPatronsAbility(userId));
//
//            if (!groupBuilderMap.containsKey(groupId)) {
//                groupBuilderMap.put(groupId, TongBingProto.CrossTongBingGetMemberRespMsg.newBuilder().setActivityId(activityId));
//            }
//            groupBuilderMap.get(groupId).addMember(tmp);
//        }
//
//        for (Map.Entry<Integer, TongBingProto.CrossTongBingGetMemberRespMsg.Builder> entry : groupBuilderMap.entrySet()) {
//            int groupId = entry.getKey();
//            TongBingProto.CrossTongBingGetMemberRespMsg.Builder builder = entry.getValue();
//            GamePlayerMgr.sendUnionActivityGroupPacket(CrossProtocol.C2_CROSS_TONG_BING_GET_UNION_MEMBER_RESP, builder, 0, activityId, groupId);
//        }
    }

    /**
     * 刷新分组活动的在线玩家
     */
    public static void refreshGroupActivityOnlinePlayer() {
        if (config == null) {
            return;
        }

        ActivityInfo activityInfo = config.getActivityInfo();
        if (!ActivityMgr.activityInShowTime(activityInfo)) {
            return;
        }

        if (!UnionActivityGroupHelper.needGroup(activityInfo)) {
            return;
        }

        long groupTime = UnionActivityGroupHelper.getGroupTime(activityInfo);
        if (System.currentTimeMillis() < groupTime) {
            return;
        }

        Map<Integer, UnionActivityGroup> groupMap = GameUnionActivityGroupMgr.getGroupMap(activityInfo.getActivityId());
        if (groupMap == null) {
            return;
        }

        synchronized (refreshGroupActivityMap) {
            refreshGroupActivityMap.putIfAbsent(activityInfo.getActivityId(), new HashSet<>());
            Set<Integer> set = refreshGroupActivityMap.get(activityInfo.getActivityId());

            boolean needRefresh = false;
            ArrayList<Integer> groupIdList = new ArrayList<>(groupMap.keySet());
            for (int groupId : groupIdList) {
                if (!set.contains(groupId)) {
                    needRefresh = true;
                    break;
                }
            }

            if (needRefresh) {
                getLogger().debug("suitang activity {} refresh online player.", activityInfo.getActivityId());
                for (GamePlayer player : GamePlayerMgr.getAllOnlinePlayer()) {
                    player.getModule(SuiTangModule.class).suiTangLogin();
                }
                set.addAll(groupIdList);
            }
        }
    }

    /**
     * 获取门客最高赚钱
     */
    private static String getTopPatronsAbility(long userId) {
        GamePlayer onlinePlayer = GamePlayerMgr.getOnlinePlayer(userId);
        if (onlinePlayer != null) {
            return onlinePlayer.getModule(PlayerModule.class).getUserHistoryAttribute().getAbility().toString();
        } else {
            UserHistoryAttribute userHistoryAttribute = UserHistoryAttributeBussiness.getUserHistoryAttribute(userId);
            if (userHistoryAttribute == null) {
                return "0";
            }
            return userHistoryAttribute.getAbility().toString();
        }
    }

    /**
     * 获取膜拜奖励
     */
    public static String getWorshipReward(boolean isEndPeriod){
        Map<String, ActivityConfig> activityConfigMap = ActivityMgr.getActivityConfigMap(config.getActivityId());
        ActivityConfig worshipConfig = activityConfigMap.get(isEndPeriod ? "WORSHIP_REWARD_END_PERIOD" : "WORSHIP_REWARD");
        if (worshipConfig == null) {
            return "";
        }
        String worshipRewardStr = worshipConfig.getValue();
        Map<Integer, List<Integer>> worshipRewardMap = new ConcurrentHashMap<>();
        for (String tmpParam : StringUtils.stringToStringList(worshipRewardStr, "\\|")) {
            List<String> strList = StringUtils.stringToStringList(tmpParam, "=");
            List<Integer> intList = StringUtils.stringToIntegerList(strList.get(1), ";");
            worshipRewardMap.put(Integer.valueOf(strList.get(0)), intList);
        }
        if (worshipRewardMap.isEmpty()) {
            return "";
        }
        Property rewardProperty = new Property();
        for(int goodsId : worshipRewardMap.keySet()){
            List<Integer> randomValueList = worshipRewardMap.get(goodsId);
            rewardProperty.addProperty(goodsId, BigInteger.valueOf(randomHelper.next(randomValueList.get(0),randomValueList.get(1) + 1)));
        }
        return PropertyHelper.parsePropertyToString(rewardProperty);
    }

    /*
     * 是否隋唐民心物品
     */
    public static boolean isSuiTangItem(int goodsId){
        return config != null && goodsId == config.getParamConfig().getMinXinItem();
    }

    /**
     * 拿配置
     */
    public static SuiTangConfigSync getConfig() {
        return config;
    }

    @Override
    public boolean reloadConfig() throws Exception {
        return true;
    }

    @Override
    public boolean reloadData() throws Exception {
        return true;
    }

    @Override
    public boolean stop() {
        return true;
    }

    @Override
    public boolean save() {
        return super.save();
    }
}
